package com.liarjo.my_website_api.security;

import cn.hutool.core.bean.BeanUtil;
import com.liarjo.my_website_api.security.pojo.LoginMapper;
import com.liarjo.my_website_api.security.pojo.SecurityUser;
import com.liarjo.my_website_api.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.liarjo.my_website_api.pojo.User;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class LoginService implements UserDetailsService {
    @Autowired
    private LoginMapper loginMapper;
    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = loginMapper.selectUserByUsername(username);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        // 用户基本信息
        SecurityUser securityUser = new SecurityUser();
        BeanUtil.copyProperties(user, securityUser);
        // token
        String token = jwtUtil.generateToken(user.getId().toString());
        securityUser.setToken(token);
        return securityUser;
    }

    public UserDetails selectUserById(Long userId) {
        User user = loginMapper.selectUserById(userId);
        // 用户基本信息
        SecurityUser securityUser = new SecurityUser();
        BeanUtil.copyProperties(user, securityUser);
        // 权限
        List<String> permissionList = loginMapper.selectPermissionListByUserId(user.getId());
        securityUser.setPermissionList(permissionList);
        return securityUser;
    }
}
